import axios from 'axios'
import router from '../router'
import store from '../store'

axios.interceptors.request.use(
  config => {
    // 登录页面不加token
    if (router.history.current.name !== 'login') {
      if (localStorage.getItem('FOREST_TOKEN')) { // 判断是否存在token，如果存在的话，则每个http header都加上token
        config.headers.token = JSON.parse(localStorage.getItem('FOREST_TOKEN')).token
      }
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  undefined,
  error => {
    let res = error.response
    switch (res.status) {
      case 401:
        // 返回 401 清除token信息并跳转到登录页面
        // store.commit(types.LOGOUT);
        // router.replace({
        //  path: '/login',
        //  query: {redirect: router.currentRoute.fullPath}
        // })
        console.log('未登录 或者token过期')
        break
      case 403:
        console.log('您没有该操作权限')
        break
      // alert('您没有该操作权限');
      case 500:
        // MessageBox(store.state.aginLogin + '!', store.state.tips, {
        //   confirmButtonText: store.state.detemine,
        //   cancelButtonText: '',
        //   type: 'warning'
        // }).then(() => {
        //   localStorage.removeItem('userInfo')
        //   router.replace({
        //     path: '/login',
        //     query: {redirect: router.currentRoute.fullPath}
        //   })
        // })
    }
    return Promise.reject(error.response.data) // 返回接口返回的错误信息
  })

const http = (type, url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios({
      method: type,
      url: url,
      data: params
    }).then(response => {
      resolve(response.data)
    }).catch(err => {
            reject(err)
    })
  })
}

export default http
